<?php

namespace App\Http\Controllers\Admin;

use App\Models\User\UserSession;
use Illuminate\Http\Request;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Configs;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class QyWechatController extends Controller
{
    //企业微信登录跳转验证
    public function qywechat_login(Request $request){
        global $scf_data;
        if(!empty($scf_data['host'])){
            $url = " <script language = 'javascript' type = 'text/javascript'>window.location.href = '%s';</script>";
            $host = $scf_data['host'] . "/index.html#/login";
        }else{
            $host = $request->getSchemeAndHttpHost();
            if(basename($_SERVER["DOCUMENT_ROOT"]) != "public"){ // 根目录运行
                $host .= "/public";
            }
            $url = "%s";
            $host .= "/index.html#/login";
        }
        if(!$request->input('code')){
            $host .= "?qyLoginErrMsg=code参数不存在";
            return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
        }
        $code = $request->input('code');
        $con = Configs::query()->where("mall_id", $request->mallId && $request->mallId != "undefined" ? request()->mallId : 1)->first();
        $res = file_get_contents('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$con->company_id.'&corpsecret='.$con->qy_agentSecret);
        $arr = json_decode($res,true);
        $members = file_get_contents('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$arr["access_token"].'&code='.$code);
        $user = json_decode($members,true);
        if(!isset($user["UserId"])){
            $host .= "?qyLoginErrMsg=获取用户信息失败，请检查企业微信配置";
            return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
        }
        $data = AdminUser::query()->where('wechat_id','=',$user['UserId'])->select("id", 'status')->first();

        if(empty($data)){
            $host .= "?qyLoginErrMsg=尚未绑定企业微信，请联系管理员";
            return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
        }
        if($data->status != "0"){
            $host .= "?qyLoginErrMsg=用户已经被禁用，请联系管理员";
            return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
        }
        $userSessionModel = new UserSession();
        $session_id = $userSessionModel->setSession(['admin_id'=>$data["id"]], $code);
        if(!$session_id){
            $host .= "?qyLoginErrMsg=获取登录凭证失败";
            return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
        }
        $host .= "?code={$code}";
        return !empty($scf_data['host']) ? sprintf($url, $host) : redirect(sprintf($url, $host));
    }

    //个人微信登录跳转验证
    public function wechat_login(Request $request)
    {
        if($request->input('code')){
            return redirect('/admin/logout')->withErrors("跳转异常！！！！");
        }
        $code = $request->input('code');
        $res = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.''.'&secret='.''.'&code='.$code.'&grant_type=authorization_code');
        $arr = json_decode($res,true);
        $members = file_get_contents('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$arr["access_token"].'&code='.$code);
        $user = json_decode($members,true);
        $bool = AdminUser::where('wechat_id','=',$user['UserId'])->first();
        if(!$bool){
            return redirect('/admin/logout')->withErrors("查不到用户！！！！");
        }
        Auth::guard('admin')->loginUsingId($bool->id);
        return redirect('/admin/index');
    }

}